package itsm.isperp.module.controller.app;

import itsm.isperp.framework.collection.tree.ITreeNode;
import itsm.isperp.framework.core.context.ContextHolder;
import itsm.isperp.framework.data.domain.DataRequest;
import itsm.isperp.framework.data.domain.DataResponse;
import itsm.isperp.framework.data.domain.PageResponse;
import itsm.isperp.framework.data.domain.QueryFilter;
import itsm.isperp.framework.domain.IUser;
import itsm.isperp.framework.utils.HibernateUUIDGenerator;
import itsm.isperp.framework.utils.TreeNodeUtils;
import itsm.isperp.framework.web.controller.TreeNodeController;
import itsm.isperp.framework.web.request.JqGridFilter;
import itsm.isperp.framework.web.request.JqGridFilterRuleOp;
import itsm.isperp.framework.web.request.JqGridRequest;
import itsm.isperp.framework.web.response.ResultMessage;
import itsm.isperp.module.dto.app.VAppDepartmentUser;
import itsm.isperp.module.entity.app.AppDepartment;
import itsm.isperp.module.entity.customer.CusCustomer;
import itsm.isperp.module.service.app.AppDepartmentService;
import itsm.isperp.module.service.customer.CusCustomerService;
import itsm.isperp.module.utils.ProjectDomainUtils;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

/**
 * 系统菜单控制器
 * 
 * @author lizx
 * @date 2013-1-12
 * @version V1.0
 */
@Controller
@RequestMapping("app/department")
public class AppDepartmentController extends TreeNodeController<AppDepartment> {

  /**
   * 系统菜单管理服务
   */
  @Autowired
  protected AppDepartmentService appDepartmentService;

  @Override
  public AppDepartmentService getService() {
    return this.appDepartmentService;
  }

  @Override
  public String getPageTitle() {
    return "部门管理";
  }
  
  @RequestMapping("edit")
  @Override
  public ModelAndView edit(String id, HttpServletRequest req) {
    String parentId = req.getParameter("parentId");
    String type = req.getParameter("type");
    ModelAndView mv = new ModelAndView();
    AppDepartment model;
    ITreeNode parent = null;
    if (StringUtils.isEmpty(id)) {
      Type genType = getClass().getGenericSuperclass();
      Type[] params = ((ParameterizedType) genType)
          .getActualTypeArguments();
      try {
        model = ((Class<AppDepartment>) params[0]).newInstance();
        if(StringUtils.isEmpty(type))
          model.setAreCustomerDept(false);
        else if(type.indexOf("customer")>-1)
          model.setAreCustomerDept(true);
        else if(type.indexOf("company")>-1)
          model.setAreCustomerDept(false);
        model.setId(HibernateUUIDGenerator.generate());
        QueryFilter filter = new JqGridFilter();
        if(StringUtils.isNoneBlank(parentId))
        {
          filter.addRule("parentId", JqGridFilterRuleOp.eq, parentId);
          int count = this.getService().findAllCount(filter).intValue();
          model.setOrderNum(count + 1);
        }
        

      } catch (Exception e) {
        throw new RuntimeException("实例化实体失败", e);
      }

      // 新建界面则需要设定父级菜单的值
      if (StringUtils.isEmpty(parentId)) {

        parent = TreeNodeUtils
            .creatRootTreenode(((Class<AppDepartment>) params[0]));
        parentId = "";
      } else {
        parent = this.getService().findOne(parentId);
      }

      model.setParentId(parentId);
    } else {
      model = this.getService().findOne(id);
      parent = this.getService().findOne(model.getParentId());
      if (parent == null) {
        Type genType = getClass().getGenericSuperclass();
        Type[] params = ((ParameterizedType) genType)
            .getActualTypeArguments();
        parent = TreeNodeUtils.creatRootTreenode((Class<AppDepartment>) params[0]);
      }
    }
   
    mv.addObject("model", model);
    mv.addObject("parentName", parent == null ? null : parent.getName());
    // 控制器返回到编辑的界面
    mv.setViewName(this.getModulePath() + "/edit");
    return mv;

  }

  /**
   * 组织机构管理页面
   * 
   * @return 织机构管理页面：app/department/org
   */
  @RequestMapping("org")
  public ModelAndView org(HttpServletRequest req) {
    ModelAndView mv = new ModelAndView("app/department/org");
    String type = req.getParameter("type");
    if (StringUtils.isNotBlank(type))
      mv.addObject("userType", type);
    mv.addObject("pageTitle", "组织机构管理");
    return mv;
  }

  /**
   * 组织机构管理页面
   * 
   * @return 织机构管理页面：app/department/org
   */
  @RequestMapping("orgEdit")
  public ModelAndView orgEdit(HttpServletRequest req) {
    ModelAndView mv = new ModelAndView("app/department/orgEdit");
    String type = req.getParameter("type");
    if (StringUtils.isNotBlank(type))
      mv.addObject("userType", type);
    IUser user = ContextHolder.getLoginUser();
    int dataRange=ProjectDomainUtils.getUserMaxDataRange(user);
    boolean ifControl = false;
    if(dataRange==22 || dataRange==33)
      ifControl=true;
    if(ifControl)
    {
      mv.addObject("areCustomerManager","1");
      mv.setViewName("app/department/orgEdit2");
    }else
    {
      mv.addObject("areCustomerManager","0");
    }
    mv.addObject("pageTitle", "组织机构管理");
    return mv;
  }

  @RequestMapping("delete")
  @ResponseBody
  public ResultMessage delete(String id, HttpServletRequest req) {
    if (StringUtils.isEmpty(id)) {
      return ResultMessage.failure("节点不能为空！");
    }
    // 如果本部门有人或者本部门下的子部门有人，则提示不能删除
    JqGridRequest request = new JqGridRequest();
    request.isQueryOne(true);
    request.setSelectColumns("department_treenode_path");
    request
        .addFilterRule("department_treenode_path", JqGridFilterRuleOp.cn, id);

    DataResponse<VAppDepartmentUser> users = this.appDepartmentService
        .findAllUserByRequest(request);
    if (users != null && users.size() == 1) {
      return ResultMessage.failure("此部门或子部门下存在用户，不能为空！");
    }

    this.getService().delete(id);

    return ResultMessage.newInstance(true);
  }

  @RequestMapping("getDeptTree")
  @ResponseBody
  public List<AppDepartment> getDeptTree(String id, boolean asyncLoad,
      String parentId, boolean showRoot, String type, String lev,
      HttpServletRequest req) {
    if(StringUtils.isEmpty(parentId))
      asyncLoad=true;
    if (StringUtils.isNotBlank(type) && asyncLoad) {
      if (StringUtils.isBlank(lev))
        lev = "10";
      String[] columns = {
          "id",
          "name",
          "parent_id",
          "treenode_path",
          "treenode_name_path",
          "open",
          "case when (length(treenode_name_path)-length(replace(treenode_name_path,'/','')))="
              + (Integer.parseInt(lev) + 1) + " then 1 else leaf end as leaf" };
      JqGridRequest request = new JqGridRequest();

      JdbcTemplate jdbcTemplate = ContextHolder.getSpringBean("jdbcTemplate");

      if (type.equals("customer"))// 只显示客户的组织
      {
        request.addFilterRule("are_customer_dept", JqGridFilterRuleOp.eq, "1");
      } else if (type.equals("company"))// 只显示客户的组织
      {
        request.addFilterRule("are_customer_dept", JqGridFilterRuleOp.eq, "0");
      }

      request.setSelectColumns(columns);
      request.isPageable(false);
      request.setSort("order_num", Direction.ASC);
      List<AppDepartment> tree = null;
      if (StringUtils.isNotEmpty(id)) {
        request.addFilterRule("parent_id", JqGridFilterRuleOp.eq, id);
        request
            .setSearchString("(length(treenode_name_path)-length(replace(treenode_name_path,'/','')))<"
                + (Integer.parseInt(lev) + 2));
        tree = this.getService().getRepository().findAllByRequest(request)
            .getContent();
      } else {
        IUser user = ContextHolder.getLoginUser();
        int dataRange=ProjectDomainUtils.getUserMaxDataRange(user);
        boolean ifControl = false;
        if(dataRange==22 || dataRange==33)
          ifControl=true;
        if(ifControl)
        {
          String sql = "select app_department_id from app_user where name='"
              + user.getUsername() + "' and app_department_id is not null";
          List<Map<String, Object>> list = jdbcTemplate.queryForList(sql);
          if (list.size() > 0) {
            String deptId = list.get(0).get("app_department_id").toString();
            request.addFilterRule("id", JqGridFilterRuleOp.eq, deptId);
          }
        }else
        {
          request.addFilterRule("parent_id", JqGridFilterRuleOp.isnull, id);
        }
       
        tree = this.getService().getRepository().findAllByRequest(request)
            .getContent();

        for (AppDepartment t : tree) {
          if (t.isOpen()) {
            DataRequest request2 = new JqGridRequest()
                .setSelectColumns(columns).isPageable(false)
                .setSort("order_num", Direction.ASC);
            request2.addFilterRule("parent_id", JqGridFilterRuleOp.eq,
                t.getId());
            t.setChildren(this.getService().getRepository()
                .findAllByRequest(request2).getContent());
          }
        }

      }
      if (id == null && showRoot) {
        Class<AppDepartment> clazz = (Class<AppDepartment>) ((ParameterizedType) getClass()
            .getGenericSuperclass()).getActualTypeArguments()[0];
        AppDepartment root = TreeNodeUtils.creatRootTreenode(clazz);
        List<AppDepartment> l = new ArrayList<>();
        root.setChildren(tree);
        l.add(root);
        return l;
      }
      return tree;
    } else {
      return this.getService().getTree(parentId, showRoot);
    }

  }

  @RequestMapping("getCusUserTree")
  @ResponseBody
  public List<AppDepartment> getCusUserTree(String id, boolean asyncLoad,
      String parentId, boolean showRoot, String type, String lev,
      HttpServletRequest req) {
    {

      String pId = "";
      IUser user = ContextHolder.getLoginUser();
      int dataRange=ProjectDomainUtils.getUserMaxDataRange(user);
      boolean ifControl = false;
      if(dataRange==22 || dataRange==33)
        ifControl=true;

      if (ifControl) {
        JdbcTemplate jdbcTemplate = ContextHolder.getSpringBean("jdbcTemplate");
        String sql = "select app_department_id from app_user where name='"
            + user.getUsername() + "' and app_department_id is not null";
        List<Map<String, Object>> list = jdbcTemplate.queryForList(sql);
        if (list.size() > 0) {
          String deptId = list.get(0).get("app_department_id").toString();
          pId = deptId;
        }

      }
      return this.getService().getTree(pId, showRoot);
    }

  }

  @RequestMapping("manageEdit")
  public ModelAndView manageEdit(HttpServletRequest req) {
    ModelAndView mv = new ModelAndView("app/department/manageEdit");
    String type = req.getParameter("type");
    String pid = req.getParameter("pid");
    if (StringUtils.isNotBlank(type))
      mv.addObject("ctype", type);
    if(StringUtils.isNotBlank(pid))
      mv.addObject("pid", pid);
    return mv;
  }

  @RequestMapping(value = { "providerDeptEdit" })
  public ModelAndView providerDeptEdit(HttpServletRequest req) {
    ModelAndView mv = new ModelAndView("app/department/providerDeptEdit");
    String type = req.getParameter("type");
    String pid = req.getParameter("pid");
    if (StringUtils.isNotBlank(type))
      mv.addObject("ctype", type);
    if(StringUtils.isNotBlank(pid))
    {
      CusCustomerService cusCustomerService=ContextHolder.getSpringBean("cusCustomerService");
      CusCustomer cus=cusCustomerService.findOne(pid);
      if(cus.getDepartmentId()!=null)
      {
        mv.addObject("pid", cus.getDepartmentId());
      }
      
    }
      
    return mv;
  }

  @Override
  public PageResponse<AppDepartment> list(JqGridRequest request,
      HttpServletRequest req) {
    // TODO Auto-generated method stub
    request.setSort("order_num", Direction.ASC);
    String term = req.getParameter("term");
    String type = req.getParameter("type");
    String op = req.getParameter("op");

    if (type != null) {
      if (type.equals("customer"))// 只显示客户的组织
      {
        request.addFilterRule("are_customer_dept", JqGridFilterRuleOp.eq, "1");
      } else if (type.equals("company"))// 只显示客户的组织
      {
        request.addFilterRule("are_customer_dept", JqGridFilterRuleOp.eq, "0");
      }
    }

    if (StringUtils.isNotEmpty(term)) {
      request.isPageable(false);
      request.setRows(15);
      if (StringUtils.isNotBlank(op) && op.equals("eq")) {
        request.setSearchString(" name='" + term + "'");
      } else {
        request.setSearchString(" treenode_name_path LIKE '%" + term + "%'");
      }

      return this.getService().findAll(request).toPage();

    } else {
      return this.getService().findAll(request).toPage();
    }
  }
  
  @ResponseBody
  @RequestMapping("search")
  public PageResponse<AppDepartment> search(JqGridRequest request,
      HttpServletRequest req) {
    // TODO Auto-generated method stub
    request.setSort("order_num", Direction.ASC);
    String term = req.getParameter("term");
    String type = req.getParameter("type");
    String op = req.getParameter("op");
   
    request.addFilterRule("are_customer_dept", JqGridFilterRuleOp.eq, "1");

    if (StringUtils.isNotEmpty(term)) {
      request.isPageable(false);
      request.setRows(15);
      if (StringUtils.isNotBlank(op) && op.equals("eq")) {
        request.setSearchString(" name='" + term + "'");
      } else {
        request.setSearchString(" name LIKE '%" + term + "%'");
      }
      request.setSelectColumns("id","name","parent_id","1 AS leaf","treenode_path");

      return this.getService().findAll(request).toPage();

    } else {
      return this.getService().findAll(request).toPage();
    }
  }
  

}
